Ext.ns('IDB');

Array.prototype.EACH_END = "$$$^&*!$$$";
Array.prototype.each = function(fn , scope) {
    var len = this.length;
    for(var i = 0 ; i < len ; i++) {
        var result = fn.call(scope || this, this[i] , i);
        if(result === this.EACH_END) {
            break;
        }
    }
};
String.prototype.contains = function(str) {
    return this.indexOf(str) != -1;
};
String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
};
String.prototype.filterNull = function() {
    if(this == 'null') {
        return null;
    }
    return this;
};
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    return s.join("");
}

var commons_tools = {
    getSizeName:function(size , fixed) {
        size = size*1;
        if(size) {
            fixed = fixed || 0;
            if(size < 1024) {
                return size.toFixed(fixed) + "B";
            }
            if(size < 1024 * 1024) {
                return (parseFloat(size) / 1024).toFixed(fixed) + "KB";
            }
            if(size < 1024 * 1024 * 1024) {
                return (parseFloat(size) / 1024 / 1024).toFixed(fixed) + "MB";
            }
            if(size < 1024 * 1024 * 1024 * 1024) {
                return (parseFloat(size) / 1024 / 1024 / 1024).toFixed(fixed) + "GB";
            }
            return (parseFloat(size) / 1024 / 1024 / 1024 / 1024).toFixed(fixed) + "TB";
        }else {
            return "0B";
        }
    },
    numberWithCommas: function (num) {//将整数1234567转换为1,234,567
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
};
var objectTypeMap = {
    table : title.table,
    view : title.view,
    progobjs: title.program
/*    produce : '存储过程',
    func : '函数',
    event : '事件',
    trigger :'触发器'
    */
};

var objectDisplayTypeMap = {
    table : title.table,
    view : title.view,
    func : title.func,
    'function' : title.func,
    func_scalar: title.func,
    func_table: title.func,
    func_view: title.func,
    function_scalar: title.func,
    function_table: title.func,
    function_view: title.func,
    proc : title.procedure,
    procedure: title.procedure,
    event : title.event,
    trigger : title.trigger
};

var operationMap = {
    'create' : menu.New,
    'change' : menu.modify,
    'delete' : menu.drop
};
var renderSize = function(v) {
    if(v >= 1024 * 1024 * 1024) {
        return (v / 1024 / 1024 / 1024).toFixed(2) + "G";
    }else if(v >= 1024 * 1024) {
        return (v / 1024 / 1024).toFixed(2) + "M";
    }else if(v >= 1024) {
        return (v / 1024).toFixed(0) + "K";
    }else {
        return v + "B";
    }
};
var getObjectCNameByEName = function(name) {
    return objectDisplayTypeMap[name];
};
function downLoadFileByURL(url) {
    var iframeEle = document.createElement("iframe");
    iframeEle.src = url;
    iframeEle.style.display = "none";
    document.body.appendChild(iframeEle);
}
String.prototype.htmlDecode = function() {
    return Ext.util.Format.htmlDecode(this);
};
String.prototype.htmlEncode = function() {
    return Ext.util.Format.htmlEncode(this);
};
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
};
String.prototype.byteLength = function () {
    var l = 0;
    for (var i = 0; i < this.length; i++) {
        c = this.charCodeAt(i);
        if (c < 256) {
            l = l + 1;
        } else {//汉字
            l = l + 2;
        }
    }
    return l;
};
Ext.define('IDB.FormPanel' , {
    extend:'Ext.form.Panel',
    config:{
        //border:true,
        buttonAlign:'center',
        timeout:120,
        defaults:{
            autoFitErrors:false,//自动调整错误提示时候的宽度
            labelSeparator:' : ',
            labelWidth:80,
            allowBlank:false,
            labelAlign:'right',
            xtype:'textfield',
            msgTarget:'side'
        }
    },
    constructor:function(config) {
        config = config || {};
        var defaults = null;
        if(config.defaults) {
            defaults = config.defaults;
            Ext.applyIf(defaults, this.config.defaults);
        }
        Ext.applyIf(config, this.config);
        if(defaults) {
            Ext.apply(config.defaults, defaults);
        }
        this.callParent([config]);
    },
    submit:function(config) {
        if(config.submitCallBack) {
            if(!config.success) {
                config.success = function(thiz, response) {
                    config.submitCallBack.call(this , thiz , response , true);
                }
            }
            if(!config.failure) {
                config.failure = function(thiz, response) {
                    config.submitCallBack.call(this , thiz , response , false);
                }
            }
        }
        this.callParent([config]);
    }
});

Ext.define('IDB.TabPanel' , {
    extend:'Ext.tab.Panel',
    config:{
        activeTab:0
    },
    constructor:function(config) {
        config = config || {};
        Ext.applyIf(config, this.config);
        this.callParent([config]);
    }
});

Ext.define('IDB.JsonStore' , {
    extend:'Ext.data.Store',
    config:{
        proxy:{
            type:'ajax',
            reader:{
                root:'root'
            }
        }
    },
    constructor:function(config) {
        config = config || {};
        Ext.applyIf(config, this.config);
        this.callParent([config]);
    }
});
Ext.define('IDB.CommonBoxStore' , {
    extend:'Ext.data.Store',
    autoLoad:true,
    autoDestroy:true,
    config:{
        proxy:{
            type:'ajax',
            reader:{
                root:'root',
                idProperty:'data'
            }
        },
        fields:['data' , 'label'],
        listeners:{
            beforeload:function(store , operation , opts) {
                if(operation.params && !operation.params.panelKey) {
                    operation.params.panelKey = getPaneKey();
                }else if(!operation.params) {
                    operation.params = {panelKey:getPaneKey()}
                }
                if(!operation.params.dbName && store.dbName) {
                    operation.params.dbName = store.dbName;
                }
            }
        }
    },
    constructor:function(config) {
        config = config || {};
        Ext.applyIf(config , this.config);
        if(config.url && !config.proxy.url) {
            var nowUrl =  config.url;
            if(nowUrl.indexOf("panelKey") == -1) {
                if(nowUrl.indexOf("?") != -1) {
                    nowUrl += '&';
                }else {
                    nowUrl += '?';
                }
                nowUrl += 'panelKey=' + getPaneKey();
            }
            config.proxy.url = nowUrl;
        }
        this.callParent([config]);
    }
});
Ext.define('IDB.CommonBox' , {
    extend:'Ext.form.field.ComboBox',
    type:'idbCombo',
    config:{
        listConfig:{
            emptyText: message.pleaseSelect,
            maxHeigh:400
        },
        triggerAction:'all',
        displayField:'label',
        valueField:'data',
        queryMode:'local',
        forceSelection:true,
        typeAhead:true,
        xtype:'combo'
    },
    defaultListeners: {
        select:function(combo,record,eOpts) {
            combo.selectCallBack(combo , record);
        }
    },
    selectCallBack:function(combo,record) {},
    constructor:function(config) {
        config = config || {};
        Ext.applyIf(config , this.config);
        if(!config.store && config.url) {
            config.store = new IDB.CommonBoxStore({url:config.url});
        }
        if(!config.listeners) {
            config.listeners = this.defaultListeners;
        }else {
            Ext.applyIf(config.listeners , this.defaultListeners);
        }
        var me = this;
        this.callParent([config]);

        this.store.on('load' , function() {
            if(config.loadSelectFirst) {
                me.loadSelect(me);
            }
            if(config.loadCallBack) {
                config.loadCallBack.call(me , me);
            }
        });
    },
    loadSelect:function(combo) {
        combo.selectFirst();
    },
    selectFirst:function() {
        if(this.store.getCount() > 0) {
            var record = this.store.first();
            if(record) {
                this.setValue(record.get('data'));
            }
        }
    }
});

Ext.define('IDB.TreeStore' , {
    extend:'Ext.data.TreeStore',
    constructor:function(config) {
        var defaultConfig = {
            autoLoad:true,
            root:{
                text: message.rootNode,expanded: true
            },
            proxy:{
                type:'ajax',
                reader:{
                    type: 'json' ,
                    root:'root'
                }
            }
        };
        config = config || {};
        Ext.applyIf(config , defaultConfig);
        if(config.url && !config.proxy.url) {
            config.proxy.url = config.url;
        }
        this.callParent([config]);
    },
    listeners:{
        beforeload:function(store , operation , opts) {
            if(operation.params && !operation.params.panelKey) {
                operation.params.panelKey = getPaneKey();
            }else {
                operation.params = {panelKey:getPaneKey()}
            }
            if(!operation.params.dbName && store.dbName) {
                operation.params.dbName = store.dbName;
            }
        }
    }
});
Ext.define('IDB.Window' , {
    extend:'Ext.window.Window',
    constructor:function(config) {
        var defaultConfig = {
            modal:true,layout:'fit',closable:false,buttonAlign:'center'
        };
        Ext.applyIf(config , defaultConfig);
        this.callParent([config]);
        this.show();
    }
});
Ext.Ajax.timeout = 60000;
var ajax = function(config) {
    if(!config.params) {
        config.params = {panelKey:getPaneKey()};
    }else if(!config.params.panelKey) {
        config.params.panelKey = getPaneKey();
    }
    Ext.Ajax.request(config);
};
var ajaxLongTime = function(config) {
    if(!config['getDataUrl']) {
        return console.log('没有获取数据的地址...');
    }
    if(!config['endCode']) {
        config['endCode'] = "END";
    }
    if(!config['times']) {
        config['times'] = 0;
    }
    if(!config['params']) {
        config['params'] = {};
    }
    if(!config['maxTimes']) {
        config['maxTimes'] = 1000;
    }
    if(!config['keyProperty']) {
        config['keyProperty'] = "id";
    }
    config['times'] = config['times'] + 1;
    if(config['times'] > config['maxTimes']) {
        var mock_result = {success:false , root:'获取结果集次数过多，可能后台已经失败...'};
        if(config['successCallBack']) {
            return config['successCallBack'].call(this , JSON.stringify(mock_result));
        }else {
            return config['success'].call(this , JSON.stringify(mock_result));
        }
    }
    var endCode = config['endCode'];
    if(config['success'] && !config['successCallBack']) {
        config['successCallBack'] = config['success'];
        config['success'] = function(resp) {
            var json = jsonDecode(resp.responseText);
            if(json.success) {
                if(json.code === endCode || json.code == 'ERROR') {
                    config['successCallBack'].call(this , resp);
                }else {
                    if(!config['startTime']) {
                        config['startTime'] = new Date().getTime();
                    }
                    if(config['notifyData']) {
                        var timeDelay = (new Date().getTime() - config['startTime']);
                        if(timeDelay > 0) {
                            config['notifyTime'].call(this , timeDelay);
                        }
                        config['notifyData'].call(this , resp , timeDelay)
                    }
                    var timeout = config['times'] * 1000;
                    var maxTimeout = config['maxRequestTimeout'];
                    if(!maxTimeout) {
                        maxTimeout = 20000;
                    }
                    if(timeout > maxTimeout){
                        timeout = maxTimeout;
                    }
                    timeout = timeout / 200;
                    var tmpTimes = 0;
                    var tmpFunction = function() {
                        tmpTimes++;
                        if(tmpTimes >= timeout) {
                            config['url'] = config['getDataUrl'];
                            if(config['times'] == 1) {
                                config['params'][config['keyProperty']] = json.root[config['keyProperty']];
                            }
                            ajaxLongTime(config);
                        }else {
                            if(config['notifyTime']) {
                                var timeDelay = (new Date().getTime() - config['startTime']);
                                if(timeDelay > 0) {
                                    config['notifyTime'].call(this , timeDelay);
                                }
                            }
                            setTimeout(tmpFunction , 200);
                        }
                    };
                    setTimeout(tmpFunction , 200);
                }
            }else {
                config['successCallBack'].call(this , resp);
            }
        }
    }
    ajax(config);
};
function jsonDecode(v , defaultV) {
    if(!v) {
        return defaultV;
    }
    return Ext.JSON.decode(v);
}
function jsonEncode(json) {return Ext.JSON.encode(json);}
function jsonToString(json) {
    if(Ext.isIE) {
        return jsonEncode(json);
    }else {
        return JSON.stringify(json);
    }
}

var createWrapperPanel = function(panel , config) {
    var nowConfig = {
        layout:'fit',
        items:[panel]
    };
    if(config) {
        Ext.applyIf(config , nowConfig);
    }else {
        config = nowConfig;
    }
    return new Ext.Panel(config);
};
var panelKey = panelKey;
var object_type = object_type;
var getPaneKey = function() {
    var panelKeyStart = '';
    if(object_type && object_type != 'null') {
        panelKeyStart = object_type + "_";
    }
    if(panelKey && panelKey != 'null') {
        return panelKeyStart + panelKey;
    }
    return panelKeyStart + "0";
};
function getFrameHtml(url) {
    return '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + url + '"></iframe>';
}
function getFrameHtmlWithId(url,id) {
    return '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + url + '" id="' + id + '"></iframe>';
}


var IDBUtil = {};

IDBUtil.showErrorMsgBox = function(title, text, errMsgList){
	var allmsgs = "";
	if(errMsgList){
		for(var i = 0; i < errMsgList.length; ++i){
			allmsgs += errMsgList[i] + "<br/>";
		}
	}
	Ext.Msg.alert(title, text + "<br/>"  + allmsgs);
};

IDBUtil.isEmptyString = function(msg){
	if( (!msg) || (!Ext.util.Format.trim(msg))){
		return true;
	}

	return false;
};

var TabUtil = {
		
};

TabUtil.calculateExistingObjPreId = function(nowDBName, objectName, objectType){
	if(objectName) {
		objectName = objectName.replaceAll('"', 'this is quoto!');
	}
	
	var preId = nowDBName + "_" + objectName + "_" + objectType;
	return preId;
};

var oracleColumnTypeArrayOld = [
                             {data:'CHAR',label:'CHAR'},
                             {data:'NCHAR',label:'NCHAR'},
                             {data:'VARCHAR2',label:'VARCHAR2'},
                             {data:'VARCHAR',label:'VARCHAR'},
                             {data:'NVARCHAR2',label:'NVARCHAR2'},
                             {data:'CLOB',label:'CLOB'},
                             {data:'NCLOB',label:'NCLOB'},
                             
                             {data:'LONG',label:'LONG'},
                             {data:'NUMBER',label:'NUMBER'},
                             
                             {data:'BINARY_FLOAT',label:'BINARY_FLOAT'},
                             {data:'BINARY_DOUBLE',label:'BINARY_DOUBLE'},
                             
                             {data:'DATE',label:'DATE'},
                             {data:'INTERVAL DAY TO SECOND',label:'INTERVAL DAY TO SECOND'},
                             {data:'INTERVAL YEAR TO MONTH',label:'INTERVAL YEAR TO MONTH'},
                             {data:'TIMESTAMP',label:'TIMESTAMP'},
                             {data:'TIMESTAMP WITH TIME ZONE',label:'TIMESTAMP WITH TIME ZONE'},
                             {data:'TIMESTAMP WITH LOCAL TIME ZONE',label:'TIMESTAMP WITH LOCAL TIME ZONE'},
                             
                             {data:'BLOB',label:'BLOB'},
                             {data:'BFILE',label:'BFILE'},
                             {data:'RAW',label:'RAW'},
                             {data:'LONG RAW',label:'LONG RAW'},
                             {data:'ROWID',label:'ROWID'},
                             
                             {data:'CHARACTER',label:'CHARACTER'},
                             {data:'CHARACTER VARYING',label:'CHARACTER VARYING'},
                             {data:'CHAR VARYING',label:'CHAR VARYING'},
                             {data:'NATIONAL CHARACTER',label:'NATIONAL CHARACTER'},
                             {data:'NATIONAL CHAR',label:'NATIONAL CHAR'},
                             {data:'NATIONAL CHARACTER VARYING',label:'NATIONAL CHARACTER VARYING'},
                             {data:'NATIONAL CHAR VARYING',label:'NATIONAL CHAR VARYING'},
                             {data:'NCHAR VARYING',label:'NCHAR VARYING'},
                             
                             {data:'NUMERIC',label:'NUMERIC'},
                             {data:'DECIMAL',label:'DECIMAL'},
                             {data:'INTEGER',label:'INTEGER'},
                             {data:'INT',label:'INT'},
                             {data:'SMALLINT',label:'SMALLINT'},
                             {data:'FLOAT',label:'FLOAT'},
                             {data:'DOUBLE PRECISION',label:'DOUBLE PRECISION'},
                             {data:'REAL',label:'REAL'},
                             {data:'(COMPLEX)',label:'(COMPLEX)'}
                            ];

var oracleColumnTypeArray = [
                             {data:'char',label:'char'},
                             {data:'varchar2',label:'varchar2'},
                             {data:'clob',label:'clob'},

                             {data:'blob',label:'blob'},
                             {data:'raw',label:'raw'},


                             {data:'number',label:'number'},


                             {data:'date',label:'date'},
                             {data:'timestamp',label:'timestamp'},

                             {data:'interval day to second',label:'interval day to second'},
                             {data:'interval year to month',label:'interval year to month'}
                            ];

var columnTypeArray = [
                       {data:'tinyint' , label:'tinyint'},
                       {data:'int' , label:'int'},
                       {data:'bigint' , label:'bigint'},
                       {data:'float' , label:'float'},
                       {data:'double' , label:'double'},
                       {data:'decimal' , label:'decimal'},
                       {data:'bit' , label:'bit'},
                       {data:'boolean' , label:'boolean'},
                       {data:'bool' , label:'bool'},
                       {data:'date' , label:'date'},
                       {data:'datetime' , label:'datetime'},
                       {data:'timestamp' , label:'timestamp'},
                       {data:'time' , label:'time'},
                       {data:'year' , label:'year'},
                       {data:'char' , label:'char'},
                       {data:'varchar' , label:'varchar'},
                       {data:'text' , label:'text'},
                       {data:'longtext' , label:'longtext'},

                       {data:'binary' , label:'binary'},
                       {data:'blob' , label:'blob'},
                       {data:'longblob' , label:'longblob'},

                       {data:'enum' , label:'enum'},
                       {data:'set' , label:'set'}
                       
                   ];
Ext.Ajax.on("beforerequest" , function(conn , options) {
    if(options.url && !options.onlyUrl && options.url.indexOf("onlyUrl=true") == -1) {
       /* if(url_namespace) {
            options.url = "/" + url_namespace + options.url;
        }*/
    }
});
Ext.Ajax.on("requestexception", function (conn, response, options) {
    var responseText = response.responseText;
    if(responseText && responseText.charAt(0) != '{' && responseText.charAt(0) != '[') {//如果不是JSON，则直接退出
        if(responseText.indexOf("Request Entity Too Large") != -1)  {
            var d = new Ext.util.DelayedTask(function(){
                Ext.Msg.alert(message.info, message.tooLarge);
            });
            d.delay(200);
        }
    }
});
Ext.Ajax.on("requestcomplete", function (conn, response, options) {
    var responseText = response.responseText;
    if(responseText && responseText.charAt(0) != '{' && responseText.charAt(0) != '[') {//如果不是JSON，则直接退出
        if(responseText.indexOf("Request Entity Too Large") != -1)  {
            var d = new Ext.util.DelayedTask(function(){
                Ext.Msg.alert(message.info, message.tooLarge);
            });
            d.delay(200);
        }
        return;
    }
    try {
    	var json = jsonDecode(responseText);
        if(json.hadLogin != undefined && !json.hadLogin) {
        	if (window.parent && window.parent != window) {
                window.parent.sessionOutCallBack(message.sessionFail);
            } else {
                sessionOutCallBack(message.sessionFail);
            }
        }
    }catch(e) {}

});
Ext.Ajax.on('beforerequest' , function(conn,options,Opts) {
    if(!options.method) {
        options.method = 'POST';
    }
});
var SimpleMap = function(data) {
    this.data = data || {};
    this.get = function(key) {
        return this.data[key] || '';
    };
    this.put = function(key , v) {
        this.data[key] = (v || null);
    };
    this.remove = function(key) {
        this.data[key] = undefined;
    };
    this.removeAll = function() {
        this.data = [];
    };
    this.contains = function(key) {
        return this.data[key] !== undefined;
    };
};
var timeoutAsynchronousAjax = function(option , sleepTime) {
    tmpAsynchronousOption = option;
    setTimeout("timeoutAsynchronousAjaxDoing()" , sleepTime);
};
var tmpAsynchronousOption = null;
var timeoutAsynchronousAjaxDoing = function() {
    asynchronousAjax(tmpAsynchronousOption);
};
//params、url、success、failure、retryUrl
var asynchronousAjax = function(option) {
    if(option.cancel)  {
        return ;
    }
    if(!option.startTryTime) {
        option.startTryTime = new Date().getTime();
    }
    if(option.onlyUrl === undefined) {
        option.onlyUrl = false;
    }
    ajax({
        url:option.url,
        timeout:3600000 * 24,
        onlyUrl:option.onlyUrl,
        params:option.params,
        success:function (response, options) {
            var json = Ext.decode(response.responseText);
            if(json.success) {
                if(option.runningCallBack) {//自定义回调
                    var result = option.runningCallBack.call(this , json , options , option);
                    if(result === undefined || result) {
                        option.url = option.retryUrl;
                        if(option.sleepTime) {
                            timeoutAsynchronousAjax(option , option.sleepTime);
                        }else {
                            timeoutAsynchronousAjax(option , 200);//重试获取数据
                        }
                    }else {
                        option.success.call(this , response , options , option);
                    }
                }else {
                    json = json.root;
                    if(json.ready) {
                        option.success.call(this , response , options);
                    }else {
                        option.url = option.retryUrl;
                        option.params.asynchronousKey = json.asynchronousKey;
                        if(!option.tryTime) {
                            option.tryTime = 1;
                        }else {
                            option.tryTime = option.tryTime + 1;
                        }
                        if(!option.userConfigTime) {
                            var timeDelay = new Date().getTime() - option.startTryTime;
                            var stepStart = 60;
                            if(timeDelay >= 600000) {
                                stepStart = 10000;
                            }else if(timeDelay >= 300000) {
                                stepStart = 5000;
                            }else if(timeDelay >= 20000) {
                                stepStart = 2000;
                            }else if(timeDelay >= 10000) {
                                stepStart = 1000;
                            }else if(timeDelay >= 5000) {
                                stepStart = 500;
                            }
                            option.params.maxTryTime = 30000;
                            option.params.stepStart = stepStart;
                        }
                        asynchronousAjax(option);//重试获取数据
                    }
                }
            }else {
                option.success.call(this , response , options);
            }
        },
        failure:function (response, options) {
            if(option.failure) {
                option.failure.call(this , response , options);
            }
        }
    });
};

var public_fun = {
    setInstanceOtherName:function() {
        var value = filterNullStr(instance_other_name) || '';
        var form = new IDB.FormPanel({
            items:[{
                fieldLabel: message.instanceAlias, width:450,
                maxLength:32,
                margin: '5 0 0 0',
                value:value,
                name:'otherName',
                blankText: message.instanceAlias + message.notEmpty,
                maxLengthText: message.exceedChar
            }]
        });
        var win = new IDB.Window({
            title: menu.set + " " + message.instanceAlias ,width:500,height:105,items:[form],
            buttons:[{
                text: message.button.confirm, handler:function() {
                    if(form.isValid()) {
                        var params = form.getValues();
                        ajax({
                            onlyUrl:true,
                            url:'/userConfig/setInstanceOtherName.do',
                            params:params,
                            success:function(resp) {
                                var json = jsonDecode(resp.responseText);
                                if(json.success) {
                                    $.feedbackMessage({
                                        type: 'success',
                                        message: message.aliasSuccess
                                    });
                                    instance_other_name = json.root;
                                    setDocumentTitle(json.root);//后台返回真正的别名，会过滤特殊字符
                                    win.close();
                                }else {
                                    $.feedbackMessage({
                                        type: 'danger',
                                        message: json.root
                                    });
                                }
                            }
                        });
                    }
                }
            },{
                text: message.button.cancel, handler:function() {win.close();}
            }]
        });
    },
    toPage:function(url) {
        window.open(url);
    }
};
var filterNullStr = function(str) {
    return (str == 'null') ? null : str;
};
var confirmSetInstanceTitle = function() {
    Ext.Msg.confirm(message.info, message.firstAlias, function(v) {
        if(v == 'yes') {
            public_fun.setInstanceOtherName();
        }
    });
};
var setDocumentTitle = function(otherName) {
    var title = connect_user + "@" + connect_ip + ":" + connect_port + "（" + now_db_type + "）";
    if(otherName && otherName != 'null') {
        title = otherName + " - " + title;
    }
    document.title = title;
};

var isNoZeroEmpty = function(_value){
	if (_value === null || _value === NaN || _value === undefined) {
		return true;
	}
	return false;
};
var getConnStr = function() {
    try {
        if (window.parent && window.parent != window && window.parent.connect_ip) {
            return window.parent.connect_ip + ":" + window.parent.connect_port;
        }
    }catch(e) {}
    return connect_ip + ":" + connect_port;
};
var getDBVersion = function() {
    try {
        if (window.parent && window.parent != window && window.parent.db_version) {
            return window.parent.db_version;
        }
    }catch(e) {}
    return db_version;
};
var maskBodyOrWin = function(msg , win) {
    if(win) {
        win.getEl().mask(msg);
    }else {
        Ext.getBody().mask(msg);
    }
};
var unMaskBodyOrWin = function(msg , win) {
    if(win) {
        win.getEl().unmask();
    }else {
        Ext.getBody().unmask();
    }
};

var tpl_tools = {
    SimpleTPL : function(content) {
        this.tokens = [];
        this.openToken = "{{";
        this.endToken = "}}";

        this.init = function() {
            var startIndex = 0;
            var length = content.length;
            while(startIndex < (length - 1)) {
                var index = content.indexOf(this.openToken , startIndex);
                if(index != -1) {
                    this.tokens.push({type:'simple',content:content.substring(startIndex , index)});
                    startIndex = index;
                    index = content.indexOf(this.endToken , startIndex);
                    if(index != -1) {
                        this.tokens.push({type:'token',content:content.substring(startIndex + 2 , index)});
                        startIndex = index + 2;
                    }else {
                        this.tokens.push({type:'simple',content:content.substring(startIndex)});
                        break;
                    }
                }else {
                    this.tokens.push({type:'simple',content:content.substring(startIndex)});
                    break;
                }
            }
        };
        this.getRealContent = function(json) {
            var content = '';
            this.tokens.each(function(row) {
                if(row.type == 'token') {
                    var curObj = json;
                    var names = row.content.split(".");
                    names.each(function(row) {
                        curObj = curObj[row];
                        if(curObj === undefined) {
                            curObj = "";
                            return this.EACH_END;
                        }
                    });
                    content += curObj;
                }else {
                    content += row.content;
                }
            });
            return content;
        };

        this.init();
    }
};